package com.ecelin;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class 填充模板 {
    public static void main(String[] args) throws Exception {
        // 读取模板流
        InputStream is = 填充模板.class.getClassLoader().getResourceAsStream("template.pdf");
        PdfReader reader = new PdfReader(is);
        // 临时输出流-表单
        ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos1);

        // 获取表单
        AcroFields form = stamper.getAcroFields();
        form.setGenerateAppearances(true);

        // 表单填充
        form.setField("txtEmpName", "张三");
        form.setField("txtManagerName", "王麻子");
        form.setField("txtCompanyName", "重庆吆不到台责任有限公司");
        form.setField("dtmCurrentDate", "2025-03-25 12:12:12");
        form.setField("dtmStartDate", "2025-03-25");
        form.setField("dtmEndDate", "2025-03-26");
        form.setField("txtCustomerName", "李四");
        form.setField("txtContactName", "13888888888");
        form.setField("numSale", "100");
        form.setField("numBudget", "1000");
        form.setField("txtMilestones", "LS节点");
        stamper.close();

        // 将填充后的PDF写入到桌面文件
        String desktopPath = System.getProperty("user.home") + "/Desktop/filled_template.pdf";
        try (FileOutputStream fos = new FileOutputStream(desktopPath)) {
            fos.write(bos1.toByteArray());
        }
	    System.out.println("执行完毕!");
    }
}
